// pages/cart/index.js
import regeneratorRuntime from '../../lib/runtime/runtime';
import {request} from '../../request/index.js'
Page({
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },
  onShow() {
    const address = wx.getStorageSync("address");
    let cart = wx.getStorageSync("cart");

    cart = cart.filter(v => v.checked);

    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      totalPrice += v.num * v.data.message.goods_price;
      totalNum += v.num;
    });
    this.setData({
      address,
      cart,
      totalPrice,
      totalNum
    });
  },

  // 支付
  async handleOrderPay() {
    const token = wx.getStorageSync('token')
    // 判断缓存中有无 token
    if(!token) {
      wx.navigateTo({
        url:'/pages/auth/index'
      })
      return
    }
    console.log('token');

    // 创建订单
    // 准备请求头参数
    const header = {Authorization:token};
    // 准备请求体参数
    const order_price = this.data.totalPrice;
    const consignee_addr = this.data.address.all;
    const cart = this.data.cart;
    let goods = [];
    cart.forEach(v => {
      goods_id: v.goods_id;
      goods_number: v.num;
      goods_price: v.goods_price;
    })
    const orderParams = {order_price,consignee_addr,goods}
    // 发送请求 创建订单
    const {order_number} = await request({
      url:'/my/orders/create', method:'POST', data:orderParams,header:header})
    // console.log(res);
    // 发起 预支付接口
    const res = await request({
      url:'/my/orders/req_unifiedorder', 
      method:'POST', 
      data:{order_number}, 
      header:header})
    console.log(res);
  }

})
